/**
 * Created by singemazuo on 1/27/16.
 */
var express = require('express'),mongoose = require('mongoose');
var Schema = mongoose.Schema;
var sha1 = require('sha1');

var db = mongoose.createConnection('localhost','GoodHome');

db.on('error',console.error.bind(console,'连接错误'));
db.once('open',function(){

});
//mongoose.connect('mongodb://localhost:27017');
// var db = mongoose.connection;

var UserSchema = new Schema({
    photo:String,
    password:String,
    mail:String,
});

var User = db.model('User',UserSchema);
module.exports = User;

module.exports.add = function(user,callback){
    var photo = new Buffer(user.photo,'utf8');
    var password = new Buffer(user.password,'utf8');

    var new_user = new User({photo:sha1(photo),password:sha1(password),mail:user.email});
    new_user.save(function(err){
        if (err){
            callback(err);
        }else{
            callback(null);
        }
    });
};

module.exports.find = function(user,callback){
    var photoBuffer = new Buffer(user.photo);
    var passwordBuffer = new Buffer(user.password);
    User.findOne({photo:sha1(photoBuffer),password:sha1(passwordBuffer)},function(err,user){
        if (err) {
            // user not found
            return res.send(401);
        }

        if (!user) {
            // incorrect username
            return res.send(401);
        }

        //if (!user.validPass(password)) {
        //    // incorrect password
        //    return res.send(401);
        //
        //    callback(err,user);
        //}
    });
};
